<template>
  <div class="consultation-new">
    <div class="sidebar">
      <div class="sidebar-title">在线医生</div>
      <div
        v-for="doctor in doctors"
        :key="doctor.id"
        :class="['doctor-item', doctor.id === (currentDoctor && currentDoctor.id) ? 'active' : '']"
        @click="selectDoctor(doctor)"
      >
        <img :src="doctor.avatar" class="avatar" />
        <div class="info">
          <div class="name">{{ doctor.name }}</div>
          <div class="meta">{{ doctor.specialty }} | {{ doctor.title }}</div>
          <div class="status" :class="doctor.status">
            {{ getStatusText(doctor.status) }}
          </div>
        </div>
      </div>
    </div>
    <div class="chat-area">
      <div class="chat-header" v-if="currentDoctor">
        <img :src="currentDoctor.avatar" class="avatar" />
        <div class="info">
          <div class="name">{{ currentDoctor.name }}</div>
          <div class="meta">{{ currentDoctor.specialty }} | {{ currentDoctor.title }}</div>
          <div class="status" :class="currentDoctor.status">
            {{ getStatusText(currentDoctor.status) }}
          </div>
        </div>
      </div>
      <div class="chat-header" v-else>
        <span>请选择医生进行咨询</span>
      </div>
      <div class="chat-messages" ref="chatMessages">
        <div
          v-for="(msg, idx) in messages"
          :key="idx"
          :class="['msg-bubble', msg.sender === 'user' ? 'right' : 'left']"
        >
          <img
            v-if="msg.sender === 'doctor'"
            :src="currentDoctor && currentDoctor.avatar"
            class="bubble-avatar"
          />
          <div class="bubble-content">
            <div class="bubble-text">{{ msg.content }}</div>
            <div class="bubble-time">{{ msg.time }}</div>
          </div>
          <img
            v-if="msg.sender === 'user'"
            src="https://img.icons8.com/color/48/000000/user-male-circle--v2.png"
            class="bubble-avatar"
          />
        </div>
      </div>
      <div class="chat-input">
        <el-input
          v-model="newMessage"
          type="textarea"
          :rows="2"
          :placeholder="getInputPlaceholder"
          @keyup.enter.native="sendMessage"
          :disabled="!canConsult"
        />
        <el-button
          type="primary"
          @click="sendMessage"
          :disabled="!canConsult || !newMessage.trim()"
        >发送</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'ConsultationNew',
  data() {
    return {
      doctors: [],
      currentDoctor: null,
      messages: [],
      newMessage: ''
    }
  },
  computed: {
    canConsult() {
      return this.currentDoctor && this.currentDoctor.status === 'online'
    },
    getInputPlaceholder() {
      if (!this.currentDoctor) return '请选择医生进行咨询'
      if (this.currentDoctor.status === 'offline') return '医生当前离线，请稍后再试'
      if (this.currentDoctor.status === 'busy') return '医生当前忙碌，请稍后再试'
      return '请输入您的健康问题'
    }
  },
  created() {
    this.fetchDoctors();
  },
  methods: {
    getStatusText(status) {
      const statusMap = {
        online: '在线',
        offline: '离线',
        busy: '忙碌'
      }
      return statusMap[status] || '未知'
    },
    async fetchDoctors() {
      try {
        const res = await axios.get('http://localhost:3000/doctors');
        this.doctors = res.data.map(doctor => ({
          ...doctor,
          status: doctor.status === 'active' ? 'online' : 'offline'
        }));
      } catch (e) {
        this.$message && this.$message.error('加载医生列表失败');
      }
    },
    async selectDoctor(doctor) {
      if (doctor.status !== 'online') {
        this.$message.warning('该医生当前不可咨询，请选择其他医生');
        return;
      }
      this.currentDoctor = doctor;
      await this.loadMessages(doctor.id);
    },
    async loadMessages(doctorId) {
      try {
        const res = await axios.get(`http://localhost:3000/consultations?doctorId=${doctorId}`);
        // 兼容历史和新消息格式
        this.messages = (res.data || []).map(msg => ({
          content: msg.content,
          sender: msg.sender || 'doctor',
          time: msg.time || (msg.createTime ? new Date(msg.createTime).toLocaleTimeString() : '')
        }));
        this.$nextTick(this.scrollToBottom);
      } catch (e) {
        this.$message && this.$message.error('加载消息失败');
      }
    },
    async sendMessage() {
      if (!this.newMessage.trim() || !this.currentDoctor) return;
      const msg = {
        doctorId: this.currentDoctor.id,
        content: this.newMessage,
        sender: 'user',
        time: new Date().toLocaleTimeString()
      };
      try {
        await axios.post('http://localhost:3000/consultations', msg);
        this.messages.push(msg);
        this.newMessage = '';
        this.scrollToBottom();
        // 模拟医生回复
        setTimeout(() => {
          const reply = {
            doctorId: this.currentDoctor.id,
            content: '感谢您的咨询，我们会尽快为您解答。',
            sender: 'doctor',
            time: new Date().toLocaleTimeString()
          };
          this.messages.push(reply);
          this.scrollToBottom();
        }, 1000);
      } catch (e) {
        this.$message && this.$message.error('发送失败');
      }
    },
    scrollToBottom() {
      const el = this.$refs.chatMessages;
      if (el) el.scrollTop = el.scrollHeight;
    }
  }
}
</script>

<style scoped>
.consultation-new {
  display: flex;
  min-height: calc(100vh - 80px);
  background: #f7f9fb;
}
.sidebar {
  width: 270px;
  background: #fff;
  border-right: 1px solid #eee;
  padding: 0;
  overflow-y: auto;
}
.sidebar-title {
  font-weight: bold;
  font-size: 18px;
  padding: 24px 20px 12px 20px;
  border-bottom: 1px solid #f0f0f0;
  color: #409eff;
}
.doctor-item {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  cursor: pointer;
  border-bottom: 1px solid #f5f5f5;
  transition: background 0.2s;
}
.doctor-item.active, .doctor-item:hover {
  background: #e6f7ff;
}
.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 14px;
  border: 2px solid #409eff22;
}
.info .name {
  font-size: 16px;
  font-weight: 500;
}
.info .meta {
  font-size: 13px;
  color: #888;
  margin-top: 2px;
}
.info .status {
  font-size: 12px;
  margin-top: 4px;
  padding: 2px 8px;
  border-radius: 10px;
  display: inline-block;
}
.info .status.online {
  background: #67C23A;
  color: #fff;
}
.info .status.offline {
  background: #909399;
  color: #fff;
}
.info .status.busy {
  background: #E6A23C;
  color: #fff;
}
.chat-area {
  flex: 1;
  display: block;
  background: #f7f9fb;
}
.chat-header {
  display: flex;
  align-items: center;
  padding: 18px 28px;
  background: #fff;
  border-bottom: 1px solid #eee;
  min-height: 80px;
}
.chat-header .avatar {
  width: 54px;
  height: 54px;
  margin-right: 18px;
}
.chat-header .info .name {
  font-size: 18px;
  font-weight: 600;
}
.chat-header .info .meta {
  font-size: 14px;
  color: #888;
  margin-top: 3px;
}
.chat-messages {
  padding: 30px 40px 20px 40px;
  background: #f7f9fb;
  display: block;
}
.msg-bubble {
  display: flex;
  align-items: flex-end;
  margin-bottom: 18px;
}
.msg-bubble.left {
  flex-direction: row;
  justify-content: flex-start;
}
.msg-bubble.right {
  flex-direction: row-reverse;
  justify-content: flex-end;
}
.bubble-avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  margin: 0 10px;
  object-fit: cover;
  background: #fff;
  border: 1.5px solid #e0e0e0;
}
.bubble-content {
  max-width: 340px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.msg-bubble.right .bubble-content {
  align-items: flex-end;
}
.bubble-text {
  background: #fff;
  border-radius: 8px;
  padding: 10px 16px;
  font-size: 15px;
  color: #222;
  box-shadow: 0 2px 8px #e6e6e6;
  margin-bottom: 4px;
  word-break: break-all;
}
.msg-bubble.right .bubble-text {
  background: #409eff;
  color: #fff;
}
.bubble-time {
  font-size: 12px;
  color: #aaa;
  margin-top: 2px;
}
.chat-input {
  background: #fff;
  border-top: 1px solid #eee;
  padding: 18px 28px;
  display: flex;
  align-items: flex-end;
  gap: 12px;
  margin-top: 10px;
}
.chat-input .el-input {
  flex: 1;
}
.chat-input .el-button {
  min-width: 80px;
}
</style> 